from django.db import models
from django.core.exceptions import ValidationError
from users.models import Supplier
from django.db.models import F

class Category(models.Model):
    name = models.CharField(max_length=50, verbose_name='类别名称')
    description = models.TextField(verbose_name='类别描述', blank=True)
    
    class Meta:
        verbose_name = '产品类别'
        verbose_name_plural = verbose_name
        
    def __str__(self):
        return self.name

class Product(models.Model):
    product_code = models.CharField(max_length=50, verbose_name='产品编码', unique=True)
    name = models.CharField(max_length=100, verbose_name='产品名称')
    CATEGORY_CHOICES = (
        ('水果', '水果'),
        ('蔬菜', '蔬菜'),
        ('肉类', '肉类'),
        ('海鲜', '海鲜'),
    )
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products', verbose_name='产品类别')
    supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, related_name='products', verbose_name='供应商')
    unit = models.CharField(max_length=20, verbose_name='单位')
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='价格')
    cost_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='成本价', default=0)
    min_stock = models.PositiveIntegerField(default=10, verbose_name='最低库存')
    purchase_date = models.DateField(null=True, blank=True, verbose_name='进货时间')  # 新增字段
    expiry_date = models.DateField(null=True, blank=True, verbose_name='到期日')  # 新增字段
    expiry_warning = models.IntegerField(default=3, verbose_name='到期预警天数')
    description = models.TextField(verbose_name='产品描述', blank=True)
    image_url = models.CharField(max_length=255, blank=True, verbose_name='图片URL')
    STATUS_CHOICES = (
        ('active', '启用'),
        ('inactive', '停用'),
    )
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='active', verbose_name='状态')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '产品'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['category']),
            models.Index(fields=['supplier']),
            models.Index(fields=['expiry_date']),  # 添加到期日索引
        ]
        
    def __str__(self):
        return self.name

    def clean(self):
        # 检查所有关联的库存记录
        low_stock_inventories = self.inventories.filter(current_stock__lt=F('min_stock'))
        if low_stock_inventories.exists():
            warehouses = ', '.join([inv.warehouse.name for inv in low_stock_inventories])
            raise ValidationError(f'在以下仓库中库存已低于预警值，请及时补货: {warehouses}')
